﻿
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using System;
using System.Collections.Generic;
using System.Data;
using U8API.Pub;
using U8Login;
using UFIDA.U8.MomServiceCommon;


namespace U8API.Plugin
{
    public class InventoryPlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Inventoryapi";
        public static string constr = "";
        private string url = "";

        private String GetCustJs(clsLogin login, MSXML2.IXMLDOMDocument2 domhead, int operation)
        {
            try
            {
                var datatable = Common.GetUrl(constr, login.get_cAcc_Id()).Tables[0];
                var datarow = datatable.Rows[0];
                url = datarow[1] + "receiveInventory";

               DebugWriteLog.WriteLine("InventoryPlugin", "GetCustJs", url);


                String cinvcode = domhead.selectSingleNode("//cinvcode") == null ? "" : domhead.selectSingleNode("//cinvcode").nodeTypedValue.ObjToStringNull();//存货编号
                //扩展自定义项
                string sqldefine = @"select * from Inventory_extradefine with(nolock) where cInvCode='" + cinvcode + "'";

                DataSet ds = DbHelperSQL.Query(sqldefine, login.UFDataConnstringForNet);
                DataTable dt = null;
                if (ds != null && ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0];
                }
                else
                {
                    return "Nopermission";
                }

                if (dt == null || dt.Rows.Count == 0)
                {
                    return "Nopermission";
                }
                List<Inventory> custdatas = new List<Inventory>();
                if (operation != 1)
                {
                    String cinvname = domhead.selectSingleNode("//cinvname") == null ? "" : domhead.selectSingleNode("//cinvname").nodeTypedValue.ObjToStringNull(); //存货名称
                    String cinvaddcode = domhead.selectSingleNode("//cinvaddcode") == null ? "" : domhead.selectSingleNode("//cinvaddcode").nodeTypedValue.ObjToStringNull(); //存货代码
                    String cinvstd = domhead.selectSingleNode("//cinvstd") == null ? "" : domhead.selectSingleNode("//cinvstd").nodeTypedValue.ObjToStringNull(); //规格型号
                    int saleFlag = domhead.selectSingleNode("//bsale") == null ? 0 : domhead.selectSingleNode("//bsale").nodeTypedValue.ObjToInt32(); //是否销售
                    int selfFlag = domhead.selectSingleNode("//bself") == null ? 0 : domhead.selectSingleNode("//bself").nodeTypedValue.ObjToInt32(); //是否自制
                    int poFlag = domhead.selectSingleNode("//bpurchase") == null ? 0 : domhead.selectSingleNode("//bpurchase").nodeTypedValue.ObjToInt32(); //是否采购件
                    int omFlag = domhead.selectSingleNode("//bproxyforeign") == null ? 0 : domhead.selectSingleNode("//bproxyforeign").nodeTypedValue.ObjToInt32(); //是否委外
                    int batchFlag = domhead.selectSingleNode("//binvbatch") == null ? 0 : domhead.selectSingleNode("//binvbatch").nodeTypedValue.ObjToInt32(); //是否批次管控
                    String unitCode = domhead.selectSingleNode("//ccomunitcode") == null ? "" : domhead.selectSingleNode("//ccomunitcode").nodeTypedValue.ObjToStringNull(); //是否主计量单位编码
                    //string cCreatePerson = domhead.selectSingleNode("//ccreateperson").nodeTypedValue.ObjToString();//建档人  获取   报错空对象
                    #region 新加字段-2017-11-7-plf
                    //所属存货中类  cInvDefine10


                    int iMassDate = domhead.selectSingleNode("//imassdate") == null ? 0 : domhead.selectSingleNode("//imassdate").nodeTypedValue.ObjToInt32(); //保质期-smallint
                    string cInvCCode = domhead.selectSingleNode("//cinvccode") == null ? "" : domhead.selectSingleNode("//cinvccode").nodeTypedValue.ObjToString(); //材料类别--存货大类编码
                    string cInvDefine1 = domhead.selectSingleNode("//cinvdefine1") == null ? "" : domhead.selectSingleNode("//cinvdefine1").nodeTypedValue.ObjToString(); //成本对象
                    string cInvDefine2 = domhead.selectSingleNode("//cinvdefine2") == null ? "" : domhead.selectSingleNode("//cinvdefine2").nodeTypedValue.ObjToString(); //打孔
                    string cInvDefine3 = domhead.selectSingleNode("//cinvdefine3") == null ? "" : domhead.selectSingleNode("//cinvdefine3").nodeTypedValue.ObjToString(); //倒角
                    string cInvDefine4 = domhead.selectSingleNode("//cinvdefine4") == null ? "" : domhead.selectSingleNode("//cinvdefine4").nodeTypedValue.ObjToString(); ;//单双面-铜片 瓷片
                    string cInvDefine5 = domhead.selectSingleNode("//cinvdefine5") == null ? "" : domhead.selectSingleNode("//cinvdefine5").nodeTypedValue.ObjToString(); //净空房
                    string cInvDefine6 = domhead.selectSingleNode("//cinvdefine6") == null ? "" : domhead.selectSingleNode("//cinvdefine6").nodeTypedValue.ObjToString(); //最终清洗
                    string cInvDefine7 = domhead.selectSingleNode("//cinvdefine7") == null ? "" : domhead.selectSingleNode("//cinvdefine7").nodeTypedValue.ObjToString(); //表面处理
                    string cInvDefine8 = domhead.selectSingleNode("//cinvdefine8") == null ? "" : domhead.selectSingleNode("//cinvdefine8").nodeTypedValue.ObjToString(); //使用材料
                    string cinvDefine9 = domhead.selectSingleNode("//cinvdefine9") == null ? "" : domhead.selectSingleNode("//cinvdefine9").nodeTypedValue.ObjToString();//客户物料号-2017-12-01-plf   te
                    string cInvDefine10 = domhead.selectSingleNode("//cinvdefine10") == null ? "" : domhead.selectSingleNode("//cinvdefine10").nodeTypedValue.ObjToString(); //所属存货中类 
                    string DefaultWhoCode = domhead.selectSingleNode("//cdefwarehouse") == null ? "" : domhead.selectSingleNode("//cdefwarehouse").nodeTypedValue.ObjToString(); //所属存货中类 
                    int cInvDefine11 = domhead.selectSingleNode("//cinvdefine11") == null ? 0 : domhead.selectSingleNode("//cinvdefine11").nodeTypedValue.ObjToInt32(); //单元数
                    int cInvDefine12 = domhead.selectSingleNode("//cinvdefine12") == null ? 0 : domhead.selectSingleNode("//cinvdefine12").nodeTypedValue.ObjToInt32(); //
                    float cInvDefine13 = domhead.selectSingleNode("//cinvdefine13") == null ? 0 : domhead.selectSingleNode("//cinvdefine13").nodeTypedValue.ObjToFloat(); //单元面积
                    float cInvDefine14 = domhead.selectSingleNode("//cinvdefine14") == null ? 0 : domhead.selectSingleNode("//cinvdefine14").nodeTypedValue.ObjToFloat(); //
                    string cCurrencyName = domhead.selectSingleNode("//ccurrencyname") == null ? "" : domhead.selectSingleNode("//ccurrencyname").nodeTypedValue.ObjToString(); //内部图号


                    #endregion

                    #region 新增功能代码：根据存货编码获取计量单位名称-2017-11-15-plf

                    #region 新增SQL语句

                    //存货大类名称-2017-11-21-plf 
                    string cinTabsql = @"select cInvCName from InventoryClass with(nolock) where cInvCCode='" + cInvCCode + "'";
                    DataSet dshead = DbHelperSQL.Query(cinTabsql, constr);
                    DataTable dthead = null;
                    if (dshead == null || dshead.Tables.Count == 0)
                    {
                        return "Nopermission";
                    }
                    else
                    {
                        dthead = dshead.Tables[0];
                        if (dthead == null || dthead.Rows.Count == 0)
                        {
                            return "Nopermission";
                        }
                    }


                    //计量单位
                    string sqlhead = @"select ccomunitname from computationunit with(nolock) where ccomunitcode= '" + unitCode + "'";
                    DataSet dsunit = DbHelperSQL.Query(sqlhead, constr);
                    DataTable dtunit = null;
                    if (dsunit == null || dsunit.Tables.Count == 0)
                    {
                        return "Nopermission";
                    }
                    else
                    {
                        dtunit = dsunit.Tables[0];
                        if (dtunit == null || dtunit.Rows.Count == 0)
                        {
                            return "Nopermission";
                        }
                    }

                    //物料自由项
                    //string sqlfree = @"select * from bas_part with(nolock) where InvCode='" + cinvcode + "'";
                    //var freetable = DbHelperSQL.Query(sqlfree, constr, null).Tables[0];
                    #endregion

                    #endregion
                    Inventory data = new Inventory();
                    if (dt.Rows.Count == 1 && dt.Columns.Count >= 5)
                    {

                        data.Cidefine1 = dt.Rows[0][1].ObjToStringNull();//qz  小分类


                        data.Cidefine2 = dt.Rows[0][2].ObjToStringNull();//qz  材质


                        data.Cidefine3 = dt.Rows[0][3].ObjToStringNull();//qz  规格


                        data.Cidefine4 = dt.Rows[0][4].ObjToStringNull();//qz  客户料号           

                        string materialtype = "";

                        materialtype = dt.Rows[0][5].ObjToStringNull();


                        if (!string.IsNullOrEmpty(materialtype) && (materialtype.Equals("0") || materialtype.Equals("1") || materialtype.Equals("2")))
                        {
                            data.MaterialType = materialtype;//   MES分类
                        }
                        else
                        {
                            return "Nopermission";
                        }
                    }
                    else
                    {
                       DebugWriteLog.WriteLine("InventoryPlugin", "Update_After", cinvcode + "没有启用扩展自定义项");
                        return "Nopermission";
                    }


                    int StartFlag = 1;



                    data.CinvCode = cinvcode;
                    data.CinvName = cinvname;
                    data.CinvAddCode = cinvaddcode;
                    data.CinvStd = cinvstd;
                    data.CinvCCode = cInvCCode;
                    if (dthead.Rows[0]["cInvCName"] != null)
                    {
                        data.CinvCName = dthead.Rows[0]["cInvCName"].ObjToString(); //存货大类名称
                    }

                    data.UnitCode = unitCode;
                    if (dtunit.Rows[0]["ccomunitname"] != null)
                    {
                        data.UnitName = dtunit.Rows[0]["ccomunitname"].ObjToString(); //计量单位名称
                    }

                    data.StartFlag = StartFlag;
                    data.SaleFlag = saleFlag;
                    data.SelfFlag = selfFlag;
                    data.PoFlag = poFlag;
                    data.OmFlag = omFlag;
                    data.BatchFlag = batchFlag;
                    //data.Owner1 = cCreatePerson;
                    #region 2017-11-06-plf

                    data.ExpiryDate = iMassDate;
                    data.CInvDefine1 = cInvDefine1;
                    data.CInvDefine2 = cInvDefine2;
                    data.CInvDefine3 = cInvDefine3;
                    data.CInvDefine4 = cInvDefine4;
                    data.CInvDefine5 = cInvDefine5;
                    data.CInvDefine6 = cInvDefine6;
                    data.CInvDefine7 = cInvDefine7;
                    data.CInvDefine8 = cInvDefine8;
                    data.CInvDefine9 = cinvDefine9;
                    data.CInvDefine10 = cInvDefine10;
                    data.CInvDefine11 = cInvDefine11;
                    data.CInvDefine12 = cInvDefine12;
                    data.CInvDefine13 = cInvDefine13;

                    data.CCurrencyName = cCurrencyName;
                    data.DefaultWhoCode = DefaultWhoCode;
                    #endregion

                    custdatas.Add(data);
                }
                else
                {
                    if (dt != null && dt.Rows.Count == 1 && dt.Columns.Count >= 5)
                    {
                        string materialtype = "";
                        if (dt.Rows[0][5] != null)
                        {
                            materialtype = dt.Rows[0][5].ObjToString();
                        }

                        if (!string.IsNullOrEmpty(materialtype) && (materialtype.Equals("0") || materialtype.Equals("1") || materialtype.Equals("2")))
                        {
                            Inventory data = new Inventory();
                            data.CinvCode = cinvcode;
                            data.MaterialType = materialtype;
                            custdatas.Add(data);
                        }
                        else
                        {
                           DebugWriteLog.WriteLine("InventoryPlugin", "Update_After", cinvcode + "没有维护MES分类");
                            return "Nopermission";
                        }
                    }
                    else
                    {
                        return "Nopermission";
                    }
                }
                ApiRequest req = new ApiRequest();
                req.data = custdatas;
                req.orgcode = login.get_cAcc_Id();
                req.primarykey = cinvcode;
                req.operation = operation;
               DebugWriteLog.WriteLine("InventoryPlugin", "GetCustJs", req.ToJson());
                return req.ToJson();
            }
            catch (Exception e)
            {
               DebugWriteLog.WriteLine("InventoryPlugin", "Update_After", e.StackTrace);
                throw e;
            }

        }


        public bool Update_After_Plm(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            Dictionary<string, string> js;
            try
            {
                js = GetCustJsPlm(login, domhead, 2);
                //不是qz直接返回true
                if (js == null)
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServerDic(url, js, "application/x-www-form-urlencoded");
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("InventoryPlugin", "Update_After_Plm", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        private Dictionary<string, string> GetCustJsPlm(clsLogin loginObj, MSXML2.IXMLDOMDocument2 domhead, int operation)
        {        
            try
            {
                var datatable = Common.GetPlmUrl(constr, loginObj.get_cAcc_Id()).Tables[0];
                var datarow = datatable.Rows[0];
                url = datarow[1].ObjToString() + "IF_02?"; 
                string cinvcode = domhead.selectSingleNode("//cinvcode") == null ? "" : domhead.selectSingleNode("//cinvcode").nodeTypedValue.ObjToStringNull();//存货编号 
                string iInvWeight = domhead.selectSingleNode("//iinvweight") == null ? "" : domhead.selectSingleNode("//iinvweight").nodeTypedValue.ObjToStringNull();//存货编号 
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("itemid", cinvcode);
                dic.Add("weight", iInvWeight);
                //dic.Add("orgcode", loginObj.get_cAcc_Id());


                DebugWriteLog.WriteLine("InventoryPlugin", "GetCustJsPlm抛出参数", "itemid = " + cinvcode + "weight = " + iInvWeight);
                return dic;        
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("InventoryPlugin", "异常", e);
                throw e;
            }
        }
        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, 2);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
               DebugWriteLog.WriteLine("InventoryPlugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        public bool Insert_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
           DebugWriteLog.WriteLine("InventoryPlugin", "Insert_After", domhead.xml);
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, 0);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
               DebugWriteLog.WriteLine("InventoryPlugin", "Insert_After_URL", url);
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
               DebugWriteLog.WriteLine("InventoryPlugin", "Insert_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, 1);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
               DebugWriteLog.WriteLine("InventoryPlugin", "Delete_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        public bool Close_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, 3);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
               DebugWriteLog.WriteLine("InventoryPlugin", "Delete_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
    }
}
